package cn.xorange.commons.security.configuration;

import cn.xorange.commons.security.annotation.PassToken;
import cn.xorange.commons.security.constants.SecurityConstants;
import cn.xorange.commons.utils.spring.SpringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.*;


/**
 * @author : yangjian
 * date : 2024/2/27
 * description :
 */
public class IgnoreUrlConfigure {

    @Resource
    SecurityProperties securityProperties;
    @Resource
    private ApplicationContext applicationContext;
    private final static String[] knife4jUrls = new String[]{"/logout","/druid/**","/favicon.ico","/doc.html","/webjars/**","/img.icons/**","/swagger-resources/**"};

    public String[] getIgnoreStaticUrls(){
        Set<String> ignoreSet = new HashSet<>();
        List<String> ignoreList = securityProperties.getIgnoreUrls();
        ignoreSet.addAll(Arrays.asList(knife4jUrls));
        ignoreSet.addAll(ignoreList);
        return ignoreSet.toArray(new String[]{});
    }

    public String[] getPassTokenUrls(){
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = mapping.getHandlerMethods();
        Set<String> ignoreSet = new HashSet<>();
        handlerMethodMap.forEach((info,method)-> {
            if (method.getMethodAnnotation(PassToken.class) != null) {
                if(Objects.nonNull(info)){
                    if (info.getPathPatternsCondition() != null) {
                        info.getPathPatternsCondition().getPatterns().forEach(pattern -> {
                            ignoreSet.add(pattern.getPatternString());
                        });
                    }
                }

            }
        });
        return ignoreSet.toArray(new String[]{});
    }



}
